<template>
    <el-cascader ref='cascaderRef' :placeholder='placeholder' :clearable='clearable' v-model='props.modelValue' :props='propsState' @change='change' />
</template>

<script lang='ts' setup>
    import { defineProps, withDefaults, reactive, ref } from 'vue'
    const props = withDefaults(defineProps<{
        modelValue : any[],
        level? : number,
        valueField? : string,
        labelField? : string,
        loadFunc : (data:any) => Promise<any[]>,
        size? : string,
        clearable? : boolean,
        placeholder? : string
    }>(), {
        valueField : 'id',
        labelField : 'name',
        level : 3,
        clearable : true
    })

    const emit = defineEmits<{
        (e : 'change', value : any[]) : void,
        (e : 'update:modelValue', value:any[])
    }>()

    

    const propsState = reactive({
        lazy: true,
        options : [],
        lazyLoad(node, resolve) {
            const { level } = node
            props.loadFunc(node.data).then(rows => {
                resolve(rows.map(item => ({
                    value : item[props.valueField],
                    label : item[props.labelField],
                    leaf : level >= (props.level - 1),
                    ...item
                })))
            })
        }
    })

    const cascaderRef = ref()

    function change(e) {
        emit('update:modelValue', e)
        emit('change', e)
    }


</script>




